package repository

import (
	"encoding/json"
	"gorm.io/gorm"
	"guliedu/model"
	"guliedu/utils"
	"mime/multipart"
	"time"
)

type ICrmBannerRepository interface {
	// 添加轮播图
	Insert(banner *model.CrmBanner) error
	// 上传轮播图
	UploadBanner(file multipart.File, fileSize int64) (string, int)
	// 根据条件查询一页轮播图
	GetBannerListPage(page int, pageSize int) ([]model.CrmBanner, error)
	// 查询所有轮播图记录数
	SelectCount() (int64, error)
	// 查询轮播图
	Select(id string) (*model.CrmBanner, error)
	// 更新轮播图
	Update(banner *model.CrmBanner) error
	// 删除轮播图
	Delete(id string) error
	// 查询所有轮播图
	SelectAll() ([]model.CrmBanner, error)
	// 缓存banner
	CacheBanner(banners []model.CrmBanner) error
	// 获取缓存banner
	GetCacheBanner() []model.CrmBanner
}

func NewICrmBannerRepository() ICrmBannerRepository {
	return &CrmBannerRepository{mysqlDb: db}
}

type CrmBannerRepository struct {
	mysqlDb *gorm.DB
}

func (t *CrmBannerRepository) Insert(banner *model.CrmBanner) error {
	return t.mysqlDb.Create(&banner).Error
}

func (t *CrmBannerRepository) UploadBanner(file multipart.File, fileSize int64) (string, int) {
	return utils.UploadFile(file, fileSize)
}

func (t *CrmBannerRepository) GetBannerListPage(page int, pageSize int) (banners []model.CrmBanner, err error) {
	err = t.mysqlDb.Offset((page - 1) * pageSize).Limit(pageSize).Find(&banners).Error
	return
}

func (t *CrmBannerRepository) SelectCount() (count int64, err error) {
	err = t.mysqlDb.Model(&model.CrmBanner{}).Count(&count).Error
	return
}

func (t *CrmBannerRepository) Select(id string) (banner *model.CrmBanner, err error) {
	err = t.mysqlDb.Where("id = ?", id).Find(&banner).Error
	return
}

func (t *CrmBannerRepository) Update(banner *model.CrmBanner) error {
	return t.mysqlDb.Save(banner).Error
}

func (t *CrmBannerRepository) Delete(id string) error {
	return t.mysqlDb.Where("id = ?", id).Delete(&model.CrmBanner{}).Error
}

func (t *CrmBannerRepository) SelectAll() (banners []model.CrmBanner, err error) {
	err = t.mysqlDb.Find(&banners).Error
	return
}

func (t *CrmBannerRepository) CacheBanner(banners []model.CrmBanner) error {
	bannersjson, _ := json.Marshal(banners)
	return client.Set("banner:index", bannersjson, time.Hour*24).Err()
}

func (t *CrmBannerRepository) GetCacheBanner() (banners []model.CrmBanner) {
	bannersjson, _ := client.Get("banner:index").Result()
	json.Unmarshal([]byte(bannersjson), &banners)
	return
}
